package com.itheima52.mobilesafe.service;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

import com.itheima52.mobilesafe.db.dao.BlackNumberDao;

import android.app.Service;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.database.ContentObserver;
import android.net.Uri;
import android.os.Handler;
import android.os.IBinder;
import android.telecom.TelecomManager;
import android.telephony.PhoneStateListener;
import android.telephony.SmsMessage;
import android.telephony.TelephonyManager;

public class CallSafeService extends Service {

	private BlackNumberDao dao;
	private TelephonyManager tm;

	@Override
	public IBinder onBind(Intent intent) {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public void onCreate() {
		// TODO Auto-generated method stub
		super.onCreate();
		dao = new BlackNumberDao(CallSafeService.this);
		tm = (TelephonyManager) getSystemService(TELECOM_SERVICE);
		MyPhoneStateListener listener = new MyPhoneStateListener();
		tm.listen(listener, MyPhoneStateListener.LISTEN_CALL_STATE);

		InnerReceiver innerReceiver = new InnerReceiver();
		IntentFilter filter = new IntentFilter(
				"android.provider.Telephony.SMS_RECEIVED");
		filter.setPriority(Integer.MAX_VALUE);
		registerReceiver(innerReceiver, filter);

	}

	class MyPhoneStateListener extends PhoneStateListener {
		// 电话状态改变时的监听
		@Override
		public void onCallStateChanged(int state, String incomingNumber) {
			// TODO Auto-generated method stub
			super.onCallStateChanged(state, incomingNumber);
			switch (state) {
			// 电话铃响
			case TelephonyManager.CALL_STATE_RINGING:
				String mode = dao.findNumber(incomingNumber);
				if (mode.equals(1) || mode.equals(2)) {
					Uri uri = Uri.parse("content://call_log/calls");
					getContentResolver().registerContentObserver(uri, true, 
							new MyContentObserver(new Handler(),incomingNumber));
					
					
					// 挂断电话
					encall();

				}

				break;
			// 电话闲置
			case TelephonyManager.CALL_STATE_IDLE:

				break;
			// 电话接通状态
			case TelephonyManager.CALL_STATE_OFFHOOK:

				break;

			default:
				break;
			}

		}
		
		
		private class MyContentObserver extends ContentObserver{
			String incomingNumber;
			public MyContentObserver(Handler handler,String incomingNumber) {
				super(handler);
				this.incomingNumber=incomingNumber;
			}
			//当数据改变的时候调用
			@Override
			public void onChange(boolean selfChange) {
				getContentResolver().unregisterContentObserver(this);
				deleteCallLog(incomingNumber);
				super.onChange(selfChange);
			}
			
			
			
		}

		/**
		 * 挂断电话
		 */
		private void encall() {
			try {
				// 通过类加载器加载ServiceManager
				Class<?> clazz = getClassLoader().loadClass(
						"android.os.ServiceManager");
				Method method = clazz.getDeclaredMethod("getService",
						String.class);
				IBinder iBinder = (IBinder) method.invoke(null, TELECOM_SERVICE);
			//	ITelephony iTelephony = ITelephony.Stub.asInterface(iBinder);
				//iTelephony.endCall();
			
			
			
			
			} catch (ClassNotFoundException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (NoSuchMethodException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (IllegalAccessException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (IllegalArgumentException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (InvocationTargetException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}

		//删除电话号码
		public void deleteCallLog(String incomingNumber) {
			// TODO Auto-generated method stub
			Uri uri = Uri.parse("content://call_log/calls");
			getContentResolver().delete(uri, "number = ?", new String[]{incomingNumber});
			
		}

	}

	class InnerReceiver extends BroadcastReceiver {

		@Override
		public void onReceive(Context context, Intent intent) {
			Object[] objects = (Object[]) intent.getExtras().get("pdus");
			for (Object object : objects) {
				SmsMessage message = SmsMessage.createFromPdu((byte[]) object);
				String originatingAddress = message.getOriginatingAddress();
				String messageBody = message.getMessageBody();
				// 通过短信的电话号码查询拦截的模式
				String mode = dao.findNumber(originatingAddress);
				if (mode.equals("1")) {
					abortBroadcast();
				} else if (mode.equals("3")) {
					abortBroadcast();
				}

			}

		}
	}

	@Override
	public void onDestroy() {
		// TODO Auto-generated method stub
		super.onDestroy();
	}

}
